package MyFramePro.Runner;

import MyFramePro.Domain.Entity.Article;
import MyFramePro.Mapper.ArticleMapper;
import MyFramePro.Service.Impl.ArticleServiceImpl;
import MyFramePro.Utils.RedisCache;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 这里是主启动类启动时，就需要进行加载的方法
 */
@Component
public class ViewCountRunner implements CommandLineRunner {

    @Resource
    private ArticleMapper articleMapper;

    @Resource
    private RedisCache redisCache;

    @Override
    public void run(String... args) throws Exception {

        //1.查询当前用户信息，以 "ID , 浏览量" 的形式展现

        List<Article> articles = articleMapper.selectList(null);    //传入空值条件，查询所有
        Map<String, Integer> viewCountMap = articles.stream()
                .collect(Collectors.toMap(article -> article.getId().toString(), article -> {
                    return article.getViewCount().intValue();   //这里需要将 Long 类型的浏览量，转换成 int 类型，不然 Redis 中存储类型异常
                }));

        //2.将当前的浏览量存储到 redis 中
        redisCache.setCacheMap("article:viewCount",viewCountMap);

    }


}
